#include "menu.h"
#include "key.h"
#include <stdio.h>
Menu *root_menu = NULL;  // 根菜单指针
Menu *tail_menu = NULL;  // 尾菜单指针
Menu *rroot_menu = NULL; // 根菜单的首指针

Menu *current_menu = NULL; // 当前菜单指针
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)

SDL_Window *win = NULL;   // SDL 窗口指针
SDL_Renderer *ren = NULL; // SDL 渲染器指针
TTF_Font *font = NULL;    // SDL 字体指针
#else
#include "GUI.h"
#endif

static Menu *create_root(char *label, void (*action)(void))
{
    Menu *c_menu = (Menu *)malloc(sizeof(Menu));
    if (c_menu == NULL)
    {
        DEBUG_LOG("Failed to allocate memory for menu\n");
        return NULL;
    }
    c_menu->info = (MenuInfo *)malloc(sizeof(MenuInfo));

    c_menu->action = action;
    c_menu->up = NULL;
    c_menu->down = NULL;
    c_menu->enter = NULL;
    c_menu->back = NULL;
    
    // 设置菜单项信息
    c_menu->info->label = label;
    c_menu->info->is_value = false; // 设置根菜单值无效

    if (!root_menu)
    {
        c_menu->info->status = MENU_IS_CHOSEN; // 设置根菜单状态为已选择
        root_menu = c_menu;                    // 设置根菜单
        rroot_menu = c_menu;                   // 设置根菜单的首指针
        tail_menu = c_menu;                    // 初始化尾菜单
    }
    else
    {
        c_menu->info->status = MENU_IS_UNCHOSEN; // 设置新菜单状态为未选择
        tail_menu->down = c_menu;                // 将新菜单添加到尾部
        c_menu->up = tail_menu;
        tail_menu = c_menu; // 更新尾菜单指针
    }
    return c_menu;
}
static Menu *create_child(Menu *dad, char *label, void (*action)(void),Number value)
{
    if (!dad)
    {
        DEBUG_LOG("Parent menu is NULL, cannot create child menu\n");
        return NULL;
    }
    Menu *son = (Menu *)malloc(sizeof(Menu));
    if (son == NULL)
    {
        DEBUG_LOG("Failed to allocate memory for child menu\n");
        return NULL;
    }
    son->info = (MenuInfo *)malloc(sizeof(MenuInfo));

    son->action = action;
    son->up = NULL;
    son->down = NULL;
    son->enter = NULL;
    son->back = dad;

    // 设置菜单项信息
    son->info->label = label;
    son->info->value = value; 
    son->info->is_value = true; // 设置子菜单值有效

    if (dad->enter == NULL)
    {
        son->info->status = MENU_IS_CHOSEN; // 设置新子菜单状态为已选择
        dad->enter = son;
    }
    else
    {

        Menu *current = dad->enter; // 获取当前子菜单
        while (current)
        {
            if (current->down == NULL)
            {
                son->info->status = MENU_IS_UNCHOSEN; // 设置新子菜单状态为已选择
                son->up = current;                    // 设置新子菜单的上级为当前子菜单
                current->down = son;                  // 将新子菜单添加到最后一个子菜单的下方
                break;
            }
            current = current->down; // 遍历到最后一个子菜单
        }
    }

    return son;
}
Menu *menu_create(Menu *dad, Menu *son, 
                  char *label, int type, void (*action)(void), Number value)
{
    Menu *new_menu = (Menu *)malloc(sizeof(Menu));
    new_menu->info = (MenuInfo *)malloc(sizeof(MenuInfo));
    switch (type)
    {
    case MENU_TYPE_ROOT:
        new_menu = create_root(label, action);
        /* code */
        break;
    case MENU_TYPE_CHILD:
        new_menu = create_child(dad, label, action,value);
        /* code */
        break;
    default:
        break;
    }
    return new_menu;
}
void menu_src_init(void(*w))
{
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
    if (TTF_Init() != 0)
    {
        SDL_Quit();
        return 0;
    }

    win = (SDL_Window *)w; // 设置 SDL 窗口指针
    ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED);
    font = TTF_OpenFont("MSYH.TTC", MENU_TEXT_SIZE);
    if (!font)
    {
        fprintf(stderr, "Failed to load font: %s\n", TTF_GetError());
        exit(1);
    }
#endif
}

void render_text(const char *text, int x, int y, SDL_Color c)
{

    SDL_Surface *surf = TTF_RenderUTF8_Blended(font, text, c);
    SDL_Texture *tex = SDL_CreateTextureFromSurface(ren, surf);
    SDL_SetTextureScaleMode(tex, SDL_ScaleModeLinear); // 设置纹理缩放模式为线性

    int w = 0, h = 0;
    TTF_SizeUTF8(font, text, &w, &h);
    SDL_Rect dst = {x, y, w, h};
    SDL_RenderCopy(ren, tex, NULL, &dst);
    SDL_FreeSurface(surf);
    SDL_DestroyTexture(tex);
}
void menu_gui_event(void)
{
    if (current_menu == NULL) // 如果当前菜单为空，直接返回
    {
        current_menu = root_menu; // 从根菜单开始
    }

    int index = 0;
    SDL_SetRenderDrawColor(ren, 0, 0, 0, 255);
    SDL_RenderClear(ren);
    while (current_menu && current_menu->info->status != MENU_IS_OPENED)
    {
        if (current_menu->info->status == MENU_IS_CHOSEN)
        {
            render_text(current_menu->info->label, 10, 10 + index * MENU_TEXT_SIZE, (SDL_Color){0, 255, 0, 255});
            if (current_menu->info->is_value)
            {
                char str[20];
                sprintf(str, "%d", current_menu->info->value.ints);
                render_text(str, MENU_WIDTH/2,MENU_HEIGHT/2, (SDL_Color){255, 255, 255, 255});
            }
        }
        else
        {
            render_text(current_menu->info->label, 10, 10 + index * MENU_TEXT_SIZE, (SDL_Color){255, 255, 255, 255});
        }

        index++;
        current_menu = current_menu->down; // 遍历所有菜单项
    }
    SDL_RenderPresent(ren);
}

void menu_event(void)
{
    current_menu = root_menu; // 从根菜单开始
    while (current_menu)
    {
        printf("Menu: %s\n", current_menu->info->label);
        // Menu *current_menu_child = current_menu->enter;  // 获取当前菜单的子菜单
        // while (current_menu_child)
        // {
        //     printf("-Child: %s\n", current_menu_child->label);
        //     current_menu_child = current_menu_child->down;  // 遍历子菜单
        // }
        current_menu = current_menu->down; // 遍历所有菜单项
    }
}
void menu_key_event(SDL_Keycode key)
{
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
#endif
    switch (key)
    {
    case KEY_DOWN:
        current_menu = root_menu;
        while (current_menu)
        {
            if (current_menu->info->status == MENU_IS_CHOSEN)
            {
                current_menu->info->status = MENU_IS_UNCHOSEN; // 设置当前菜单项状态为未选择
                break;                                         // 找到当前菜单项后退出循环
            }
            current_menu = current_menu->down;
        }
        if (current_menu->down)
        {
            current_menu->down->info->status = MENU_IS_CHOSEN; // 设置当前菜单项状态为已选择
        }
        else
        {
            current_menu = root_menu;                    // 如果没有下一个菜单项，回到根菜单
            current_menu->info->status = MENU_IS_CHOSEN; // 设置根菜单状态为已选择
        }
        DEBUG_LOG("Key Down Pressed\n");
        break;
    case KEY_UP:
        current_menu = tail_menu; // 从尾菜单开始
        while (current_menu)
        {
            if (current_menu->info->status == MENU_IS_CHOSEN)
            {
                current_menu->info->status = MENU_IS_UNCHOSEN; // 设置当前菜单项状态为未选择
                break;                                         // 找到当前菜单项后退出循环
            }
            current_menu = current_menu->up;
        }
        if (current_menu->up)
        {
            current_menu->up->info->status = MENU_IS_CHOSEN; // 设置当前菜单项状态为已选择
        }
        else
        {
            current_menu = tail_menu;                    // 如果没有下一个菜单项，回到尾部菜单
            current_menu->info->status = MENU_IS_CHOSEN; // 设置根菜单状态为已选择
        }
        DEBUG_LOG("Key Up Pressed\n");
        break;
    case KEY_ENTER:
        current_menu = root_menu;
        if (current_menu->enter)
        {
            while (current_menu)
            {
                if (current_menu->info->status == MENU_IS_CHOSEN)
                {
                    break; // 找到当前菜单项后退出循环
                }
                current_menu = current_menu->down;
            }
            if (current_menu->enter)
            {
                root_menu = current_menu->enter; // 进入子菜单
                current_menu = root_menu;        // 进入子菜单后，从子菜单的根开始
            }
            while (current_menu)
            {
                tail_menu = current_menu;          // 更新尾菜单指针
                current_menu = current_menu->down; // 遍历所有子菜单项
            }
        }

        DEBUG_LOG("Key Enter Pressed\n");
        break;
    case KEY_BACK:
        current_menu = root_menu;
        if (current_menu->back)
        {
            root_menu = rroot_menu; // 返回上一级菜单
        }
        current_menu = root_menu; // 返回上一级菜单后，从根菜单开始
        while (current_menu)
        {
            tail_menu = current_menu;          // 更新尾菜单指针
            current_menu = current_menu->down; // 遍历所有子菜单项
        }
        DEBUG_LOG("Key Back Pressed\n");
        break;

    case KEY_INCREMENT: // 增加值
        current_menu = root_menu;
        while (current_menu)
        {
            if (current_menu->info->status == MENU_IS_CHOSEN)
            {

                break;                                         // 找到当前菜单项后退出循环
            }
            current_menu = current_menu->down;
        }
        if (current_menu->info->is_value&& current_menu->info->value.ints < current_menu->info->value.max)  // 检查是否有值并且值未超过最大值
        {
            current_menu->info->value.ints += 1; // 增加整数值
        }
        DEBUG_LOG("Key Increment Pressed\n");
        break;
    case KEY_DECREMENT: // 减少值
        current_menu = root_menu;
        while (current_menu)
        {
            if (current_menu->info->status == MENU_IS_CHOSEN)
            {
                break;                                         // 找到当前菜单项后退出循环
            }
            current_menu = current_menu->down;
        }
        if (current_menu->info->is_value&& current_menu->info->value.ints > current_menu->info->value.min)  // 检查是否有值并且值未超过最大值
        {
            current_menu->info->value.ints -= 1; // 减少整数值
        }
        DEBUG_LOG("Key Decrement Pressed\n");
        break;
    default:
        break;
    }
}